import 'dart:convert';

import 'package:dio/dio.dart';

import 'package:freemusic/model/AbstractDiss.dart';
import 'package:freemusic/model/QQSong.dart';
import 'package:freemusic/model/qq/QQDiss.dart';

const httpHeaders = {
  "Accept": "application/json, text/javascript, */*; q=0.01",
  "Origin": "https://y.qq.com",
  "Referer": "https://y.qq.com/n/yqq/song/125587261_num.html",
  "Sec-Fetch-Mode": "cors",
  "User-Agent":
      "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.3"
};

class QQAPI {

  static final String freeSongmid = "00415NCr2qvHiO";
  static final String specParam = "format=json205361747&platform=yqq&cid=205361747&guid=126548448";

  static Future<List<QQSong>> search(String keyword, int page) async {
    Response response = await Dio().get(
        "https://c.y.qq.com/soso/fcgi-bin/client_search_cp?p=$page&n=10&w=$keyword&aggr=1&lossless=1&cr=1&format=json");

    QQSong songs = QQSong();
    return songs.fromRemoteJosn(jsonDecode(response.data));
  }

  static Future<QQSong> getSong(QQSong info) async {
    String fileName = _fileName(info.hash, info.type);
    String vkey = await _generateKey(info.hash, fileName);
    if (vkey.isEmpty) {
      info.playUrl = "";
      return info;
    }
    info.playUrl =
        "http://ws.stream.qqmusic.qq.com/$fileName?fromtag=0&guid=126548448&vkey=$vkey";
    if (info.img == null || info.img == "") {
      info.img =
          "https://y.gtimg.cn/music/photo_new/T002R300x300M000${info.albummid}.jpg";
    }

    Dio dio = Dio();
    dio.options.headers = httpHeaders;
    Response lyricsResponse = await dio.get(
        "https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_yqq.fcg?nobase64=1&musicid=${info.songid}&-=jsonp1&g_tk=5381&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq.json&needNewCode=0");
    info.setLyricsFromJson(lyricsResponse.data);

    return info;
  }

  static download(String url, String savepath) async {
    Response response = await Dio().download(url, savepath);
    return response;
  }

  static Future<Map> getSongSheet(String cookie ) async {
    Dio dio = Dio();
    dio.interceptors.add(InterceptorsWrapper(onRequest: (options){

    }));
    dio.options.headers = {
      "referer": "https://c.y.qq.com/",
      "accept": "application/json, text/javascript, */*; q=0.01",
      "Origin": "https://y.qq.com",
      "cookie": cookie,
    };
    Response response = await dio.get("https://c.y.qq.com/rsc/fcgi-bin/fcg_get_profile_homepage.fcg?cid=205360838&reqfrom=1");
    return response.data;
  }
  
  static Future<Map> getSongsByDissId(String qq, int dissId) async {
    Dio dio = Dio();
    dio.options.headers = {
      "referer": "https://c.y.qq.com/",
      "accept": "application/json, text/javascript, */*; q=0.01",
      "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36"
    };
    Response response = await dio.get("https://c.y.qq.com/qzone/fcg-bin/fcg_ucc_getcdinfo_byids_cp.fcg?type=1&utf8=1&disstid=$dissId&loginUin=$qq&format=json&platform=yqq.json");
    return response.data;
  }
  static Future<String> _generateKey(String mid, String fileName) async {
    //当试听格式为mp3是，提供一个免费歌曲的songmid，可获得任何vip 128K或m4a歌曲的vkey
    
    String url =
        "https://c.y.qq.com/base/fcgi-bin/fcg_music_express_mobile3.fcg?format=json205361747&platform=yqq&cid=205361747" +
            "&songmid=$mid" +
            "&filename=$fileName&guid=126548448";

    Response response = await Dio().get(url);
    Map result = jsonDecode(response.data);
    Map data = result['data'];
    Map item = data['items'][0];
    return item['vkey'];
  }

  static String _fileName(String mid, String type) {
    //mp3 : 128k - M500, 320k - M800 , flac - F000 
    switch (type) {
      case "m4a": 
        return "C400$mid.m4a";
      case "128k":
        return "M500$mid.mp3";
      case "320K":
        return "M800$mid.mp3";
      case "flac": 
        return "F000$mid.flac";
    }
    return "C400$mid.m4a";
    
  }
}
